shutil.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 The Python Software Foundation.
  4. # See LICENSE.txt and CONTRIBUTORS.txt.
  5. #
  6. """Utility functions for copying and archiving files and directory trees.
  7. XXX The functions here don't copy the resource fork or other metadata on Mac.
  8. """
  9. import os
  10. import sys
  11. import stat
  12. from os.path import abspath
  13. import fnmatch
  14. try:
  15. from collections.abc import Callable
  16. except ImportError:
  17. from collections import Callable
  18. import errno
  19. from . import tarfile
  20. try:
  21. import bz2
  22. _BZ2_SUPPORTED = True
  23. except ImportError:
  24. _BZ2_SUPPORTED = False
  25. try:
  26. from pwd import getpwnam
  27. except ImportError:
  28. getpwnam = None
  29. try:
  30. from grp import getgrnam
  31. except ImportError:
  32. getgrnam = None
  33. __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
  34. "copytree", "move", "rmtree", "Error", "SpecialFileError",
  35. "ExecError", "make_archive", "get_archive_formats",
  36. "register_archive_format", "unregister_archive_format",
  37. "get_unpack_formats", "register_unpack_format",
  38. "unregister_unpack_format", "unpack_archive", "ignore_patterns"]
  39. class Error(EnvironmentError):
  40. pass
  41. class SpecialFileError(EnvironmentError):
  42. """Raised when trying to do a kind of operation (e.g. copying) which is
  43. not supported on a special file (e.g. a named pipe)"""
  44. class ExecError(EnvironmentError):
  45. """Raised when a command could not be executed"""
  46. class ReadError(EnvironmentError):
  47. """Raised when an archive cannot be read"""
  48. class RegistryError(Exception):
  49. """Raised when a registry operation with the archiving
  50. and unpacking registries fails"""
  51. try:
  52. WindowsError
  53. except NameError:
  54. WindowsError = None
  55. def copyfileobj(fsrc, fdst, length=16*1024):
  56. """copy data from file-like object fsrc to file-like object fdst"""
  57. while 1:
  58. buf = fsrc.read(length)
  59. if not buf:
  60. break
  61. fdst.write(buf)
  62. def _samefile(src, dst):
  63. # Macintosh, Unix.
  64. if hasattr(os.path, 'samefile'):
  65. try:
  66. return os.path.samefile(src, dst)
  67. except OSError:
  68. return False
  69. # All other platforms: check for same pathname.
  70. return (os.path.normcase(os.path.abspath(src)) ==
  71. os.path.normcase(os.path.abspath(dst)))
  72. def copyfile(src, dst):
  73. """Copy data from src to dst"""
  74. if _samefile(src, dst):
  75. raise Error("`%s` and `%s` are the same file" % (src, dst))
  76. for fn in [src, dst]:
  77. try:
  78. st = os.stat(fn)
  79. except OSError:
  80. # File most likely does not exist
  81. pass
  82. else:
  83. # XXX What about other special files? (sockets, devices...)
  84. if stat.S_ISFIFO(st.st_mode):
  85. raise SpecialFileError("`%s` is a named pipe" % fn)
  86. with open(src, 'rb') as fsrc:
  87. with open(dst, 'wb') as fdst:
  88. copyfileobj(fsrc, fdst)
  89. def copymode(src, dst):
  90. """Copy mode bits from src to dst"""
  91. if hasattr(os, 'chmod'):
  92. st = os.stat(src)
  93. mode = stat.S_IMODE(st.st_mode)
  94. os.chmod(dst, mode)
  95. def copystat(src, dst):
  96. """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
  97. st = os.stat(src)
  98. mode = stat.S_IMODE(st.st_mode)
  99. if hasattr(os, 'utime'):
  100. os.utime(dst, (st.st_atime, st.st_mtime))
  101. if hasattr(os, 'chmod'):
  102. os.chmod(dst, mode)
  103. if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
  104. try:
  105. os.chflags(dst, st.st_flags)
  106. except OSError as why:
  107. if (not hasattr(errno, 'EOPNOTSUPP') or
  108. why.errno != errno.EOPNOTSUPP):
  109. raise
  110. def copy(src, dst):
  111. """Copy data and mode bits ("cp src dst").
  112. The destination may be a directory.
  113. """
  114. if os.path.isdir(dst):
  115. dst = os.path.join(dst, os.path.basename(src))
  116. copyfile(src, dst)
  117. copymode(src, dst)
  118. def copy2(src, dst):
  119. """Copy data and all stat info ("cp -p src dst").
  120. The destination may be a directory.
  121. """
  122. if os.path.isdir(dst):
  123. dst = os.path.join(dst, os.path.basename(src))
  124. copyfile(src, dst)
  125. copystat(src, dst)
  126. def ignore_patterns(*patterns):
  127. """Function that can be used as copytree() ignore parameter.
  128. Patterns is a sequence of glob-style patterns
  129. that are used to exclude files"""
  130. def _ignore_patterns(path, names):
  131. ignored_names = []
  132. for pattern in patterns:
  133. ignored_names.extend(fnmatch.filter(names, pattern))
  134. return set(ignored_names)
  135. return _ignore_patterns
  136. def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
  137. ignore_dangling_symlinks=False):
  138. """Recursively copy a directory tree.
  139. The destination directory must not already exist.
  140. If exception(s) occur, an Error is raised with a list of reasons.
  141. If the optional symlinks flag is true, symbolic links in the
  142. source tree result in symbolic links in the destination tree; if
  143. it is false, the contents of the files pointed to by symbolic
  144. links are copied. If the file pointed by the symlink doesn't
  145. exist, an exception will be added in the list of errors raised in
  146. an Error exception at the end of the copy process.
  147. You can set the optional ignore_dangling_symlinks flag to true if you
  148. want to silence this exception. Notice that this has no effect on
  149. platforms that don't support os.symlink.
  150. The optional ignore argument is a callable. If given, it
  151. is called with the `src` parameter, which is the directory
  152. being visited by copytree(), and `names` which is the list of
  153. `src` contents, as returned by os.listdir():
  154. callable(src, names) -> ignored_names
  155. Since copytree() is called recursively, the callable will be
  156. called once for each directory that is copied. It returns a
  157. list of names relative to the `src` directory that should
  158. not be copied.
  159. The optional copy_function argument is a callable that will be used
  160. to copy each file. It will be called with the source path and the
  161. destination path as arguments. By default, copy2() is used, but any
  162. function that supports the same signature (like copy()) can be used.
  163. """
  164. names = os.listdir(src)
  165. if ignore is not None:
  166. ignored_names = ignore(src, names)
  167. else:
  168. ignored_names = set()
  169. os.makedirs(dst)
  170. errors = []
  171. for name in names:
  172. if name in ignored_names:
  173. continue
  174. srcname = os.path.join(src, name)
  175. dstname = os.path.join(dst, name)
  176. try:
  177. if os.path.islink(srcname):
  178. linkto = os.readlink(srcname)
  179. if symlinks:
  180. os.symlink(linkto, dstname)
  181. else:
  182. # ignore dangling symlink if the flag is on
  183. if not os.path.exists(linkto) and ignore_dangling_symlinks:
  184. continue
  185. # otherwise let the copy occurs. copy2 will raise an error
  186. copy_function(srcname, dstname)
  187. elif os.path.isdir(srcname):
  188. copytree(srcname, dstname, symlinks, ignore, copy_function)
  189. else:
  190. # Will raise a SpecialFileError for unsupported file types
  191. copy_function(srcname, dstname)
  192. # catch the Error from the recursive copytree so that we can
  193. # continue with other files
  194. except Error as err:
  195. errors.extend(err.args[0])
  196. except EnvironmentError as why:
  197. errors.append((srcname, dstname, str(why)))
  198. try:
  199. copystat(src, dst)
  200. except OSError as why:
  201. if WindowsError is not None and isinstance(why, WindowsError):
  202. # Copying file access times may fail on Windows
  203. pass
  204. else:
  205. errors.extend((src, dst, str(why)))
  206. if errors:
  207. raise Error(errors)
  208. def rmtree(path, ignore_errors=False, onerror=None):
  209. """Recursively delete a directory tree.
  210. If ignore_errors is set, errors are ignored; otherwise, if onerror
  211. is set, it is called to handle the error with arguments (func,
  212. path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
  213. path is the argument to that function that caused it to fail; and
  214. exc_info is a tuple returned by sys.exc_info(). If ignore_errors
  215. is false and onerror is None, an exception is raised.
  216. """
  217. if ignore_errors:
  218. def onerror(*args):
  219. pass
  220. elif onerror is None:
  221. def onerror(*args):
  222. raise
  223. try:
  224. if os.path.islink(path):
  225. # symlinks to directories are forbidden, see bug #1669
  226. raise OSError("Cannot call rmtree on a symbolic link")
  227. except OSError:
  228. onerror(os.path.islink, path, sys.exc_info())
  229. # can't continue even if onerror hook returns
  230. return
  231. names = []
  232. try:
  233. names = os.listdir(path)
  234. except os.error:
  235. onerror(os.listdir, path, sys.exc_info())
  236. for name in names:
  237. fullname = os.path.join(path, name)
  238. try:
  239. mode = os.lstat(fullname).st_mode
  240. except os.error:
  241. mode = 0
  242. if stat.S_ISDIR(mode):
  243. rmtree(fullname, ignore_errors, onerror)
  244. else:
  245. try:
  246. os.remove(fullname)
  247. except os.error:
  248. onerror(os.remove, fullname, sys.exc_info())
  249. try:
  250. os.rmdir(path)
  251. except os.error:
  252. onerror(os.rmdir, path, sys.exc_info())
  253. def _basename(path):
  254. # A basename() variant which first strips the trailing slash, if present.
  255. # Thus we always get the last component of the path, even for directories.
  256. return os.path.basename(path.rstrip(os.path.sep))
  257. def move(src, dst):
  258. """Recursively move a file or directory to another location. This is
  259. similar to the Unix "mv" command.
  260. If the destination is a directory or a symlink to a directory, the source
  261. is moved inside the directory. The destination path must not already
  262. exist.
  263. If the destination already exists but is not a directory, it may be
  264. overwritten depending on os.rename() semantics.
  265. If the destination is on our current filesystem, then rename() is used.
  266. Otherwise, src is copied to the destination and then removed.
  267. A lot more could be done here... A look at a mv.c shows a lot of
  268. the issues this implementation glosses over.
  269. """
  270. real_dst = dst
  271. if os.path.isdir(dst):
  272. if _samefile(src, dst):
  273. # We might be on a case insensitive filesystem,
  274. # perform the rename anyway.
  275. os.rename(src, dst)
  276. return
  277. real_dst = os.path.join(dst, _basename(src))
  278. if os.path.exists(real_dst):
  279. raise Error("Destination path '%s' already exists" % real_dst)
  280. try:
  281. os.rename(src, real_dst)
  282. except OSError:
  283. if os.path.isdir(src):
  284. if _destinsrc(src, dst):
  285. raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
  286. copytree(src, real_dst, symlinks=True)
  287. rmtree(src)
  288. else:
  289. copy2(src, real_dst)
  290. os.unlink(src)
  291. def _destinsrc(src, dst):
  292. src = abspath(src)
  293. dst = abspath(dst)
  294. if not src.endswith(os.path.sep):
  295. src += os.path.sep
  296. if not dst.endswith(os.path.sep):
  297. dst += os.path.sep
  298. return dst.startswith(src)
  299. def _get_gid(name):
  300. """Returns a gid, given a group name."""
  301. if getgrnam is None or name is None:
  302. return None
  303. try:
  304. result = getgrnam(name)
  305. except KeyError:
  306. result = None
  307. if result is not None:
  308. return result[2]
  309. return None
  310. def _get_uid(name):
  311. """Returns an uid, given a user name."""
  312. if getpwnam is None or name is None:
  313. return None
  314. try:
  315. result = getpwnam(name)
  316. except KeyError:
  317. result = None
  318. if result is not None:
  319. return result[2]
  320. return None
  321. def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
  322. owner=None, group=None, logger=None):
  323. """Create a (possibly compressed) tar file from all the files under
  324. 'base_dir'.
  325. 'compress' must be "gzip" (the default), "bzip2", or None.
  326. 'owner' and 'group' can be used to define an owner and a group for the
  327. archive that is being built. If not provided, the current owner and group
  328. will be used.
  329. The output tar file will be named 'base_name' + ".tar", possibly plus
  330. the appropriate compression extension (".gz", or ".bz2").
  331. Returns the output filename.
  332. """
  333. tar_compression = {'gzip': 'gz', None: ''}
  334. compress_ext = {'gzip': '.gz'}
  335. if _BZ2_SUPPORTED:
  336. tar_compression['bzip2'] = 'bz2'
  337. compress_ext['bzip2'] = '.bz2'
  338. # flags for compression program, each element of list will be an argument
  339. if compress is not None and compress not in compress_ext:
  340. raise ValueError("bad value for 'compress', or compression format not "
  341. "supported : {0}".format(compress))
  342. archive_name = base_name + '.tar' + compress_ext.get(compress, '')
  343. archive_dir = os.path.dirname(archive_name)
  344. if not os.path.exists(archive_dir):
  345. if logger is not None:
  346. logger.info("creating %s", archive_dir)
  347. if not dry_run:
  348. os.makedirs(archive_dir)
  349. # creating the tarball
  350. if logger is not None:
  351. logger.info('Creating tar archive')
  352. uid = _get_uid(owner)
  353. gid = _get_gid(group)
  354. def _set_uid_gid(tarinfo):
  355. if gid is not None:
  356. tarinfo.gid = gid
  357. tarinfo.gname = group
  358. if uid is not None:
  359. tarinfo.uid = uid
  360. tarinfo.uname = owner
  361. return tarinfo
  362. if not dry_run:
  363. tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
  364. try:
  365. tar.add(base_dir, filter=_set_uid_gid)
  366. finally:
  367. tar.close()
  368. return archive_name
  369. def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
  370. # XXX see if we want to keep an external call here
  371. if verbose:
  372. zipoptions = "-r"
  373. else:
  374. zipoptions = "-rq"
  375. from distutils.errors import DistutilsExecError
  376. from distutils.spawn import spawn
  377. try:
  378. spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
  379. except DistutilsExecError:
  380. # XXX really should distinguish between "couldn't find
  381. # external 'zip' command" and "zip failed".
  382. raise ExecError("unable to create zip file '%s': "
  383. "could neither import the 'zipfile' module nor "
  384. "find a standalone zip utility") % zip_filename
  385. def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
  386. """Create a zip file from all the files under 'base_dir'.
  387. The output zip file will be named 'base_name' + ".zip". Uses either the
  388. "zipfile" Python module (if available) or the InfoZIP "zip" utility
  389. (if installed and found on the default search path). If neither tool is
  390. available, raises ExecError. Returns the name of the output zip
  391. file.
  392. """
  393. zip_filename = base_name + ".zip"
  394. archive_dir = os.path.dirname(base_name)
  395. if not os.path.exists(archive_dir):
  396. if logger is not None:
  397. logger.info("creating %s", archive_dir)
  398. if not dry_run:
  399. os.makedirs(archive_dir)
  400. # If zipfile module is not available, try spawning an external 'zip'
  401. # command.
  402. try:
  403. import zipfile
  404. except ImportError:
  405. zipfile = None
  406. if zipfile is None:
  407. _call_external_zip(base_dir, zip_filename, verbose, dry_run)
  408. else:
  409. if logger is not None:
  410. logger.info("creating '%s' and adding '%s' to it",
  411. zip_filename, base_dir)
  412. if not dry_run:
  413. zip = zipfile.ZipFile(zip_filename, "w",
  414. compression=zipfile.ZIP_DEFLATED)
  415. for dirpath, dirnames, filenames in os.walk(base_dir):
  416. for name in filenames:
  417. path = os.path.normpath(os.path.join(dirpath, name))
  418. if os.path.isfile(path):
  419. zip.write(path, path)
  420. if logger is not None:
  421. logger.info("adding '%s'", path)
  422. zip.close()
  423. return zip_filename
  424. _ARCHIVE_FORMATS = {
  425. 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
  426. 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
  427. 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
  428. 'zip': (_make_zipfile, [], "ZIP file"),
  429. }
  430. if _BZ2_SUPPORTED:
  431. _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
  432. "bzip2'ed tar-file")
  433. def get_archive_formats():
  434. """Returns a list of supported formats for archiving and unarchiving.
  435. Each element of the returned sequence is a tuple (name, description)
  436. """
  437. formats = [(name, registry[2]) for name, registry in
  438. _ARCHIVE_FORMATS.items()]
  439. formats.sort()
  440. return formats
  441. def register_archive_format(name, function, extra_args=None, description=''):
  442. """Registers an archive format.
  443. name is the name of the format. function is the callable that will be
  444. used to create archives. If provided, extra_args is a sequence of
  445. (name, value) tuples that will be passed as arguments to the callable.
  446. description can be provided to describe the format, and will be returned
  447. by the get_archive_formats() function.
  448. """
  449. if extra_args is None:
  450. extra_args = []
  451. if not isinstance(function, Callable):
  452. raise TypeError('The %s object is not callable' % function)
  453. if not isinstance(extra_args, (tuple, list)):
  454. raise TypeError('extra_args needs to be a sequence')
  455. for element in extra_args:
  456. if not isinstance(element, (tuple, list)) or len(element) !=2:
  457. raise TypeError('extra_args elements are : (arg_name, value)')
  458. _ARCHIVE_FORMATS[name] = (function, extra_args, description)
  459. def unregister_archive_format(name):
  460. del _ARCHIVE_FORMATS[name]
  461. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
  462. dry_run=0, owner=None, group=None, logger=None):
  463. """Create an archive file (eg. zip or tar).
  464. 'base_name' is the name of the file to create, minus any format-specific
  465. extension; 'format' is the archive format: one of "zip", "tar", "bztar"
  466. or "gztar".
  467. 'root_dir' is a directory that will be the root directory of the
  468. archive; ie. we typically chdir into 'root_dir' before creating the
  469. archive. 'base_dir' is the directory where we start archiving from;
  470. ie. 'base_dir' will be the common prefix of all files and
  471. directories in the archive. 'root_dir' and 'base_dir' both default
  472. to the current directory. Returns the name of the archive file.
  473. 'owner' and 'group' are used when creating a tar archive. By default,
  474. uses the current owner and group.
  475. """
  476. save_cwd = os.getcwd()
  477. if root_dir is not None:
  478. if logger is not None:
  479. logger.debug("changing into '%s'", root_dir)
  480. base_name = os.path.abspath(base_name)
  481. if not dry_run:
  482. os.chdir(root_dir)
  483. if base_dir is None:
  484. base_dir = os.curdir
  485. kwargs = {'dry_run': dry_run, 'logger': logger}
  486. try:
  487. format_info = _ARCHIVE_FORMATS[format]
  488. except KeyError:
  489. raise ValueError("unknown archive format '%s'" % format)
  490. func = format_info[0]
  491. for arg, val in format_info[1]:
  492. kwargs[arg] = val
  493. if format != 'zip':
  494. kwargs['owner'] = owner
  495. kwargs['group'] = group
  496. try:
  497. filename = func(base_name, base_dir, **kwargs)
  498. finally:
  499. if root_dir is not None:
  500. if logger is not None:
  501. logger.debug("changing back to '%s'", save_cwd)
  502. os.chdir(save_cwd)
  503. return filename
  504. def get_unpack_formats():
  505. """Returns a list of supported formats for unpacking.
  506. Each element of the returned sequence is a tuple
  507. (name, extensions, description)
  508. """
  509. formats = [(name, info[0], info[3]) for name, info in
  510. _UNPACK_FORMATS.items()]
  511. formats.sort()
  512. return formats
  513. def _check_unpack_options(extensions, function, extra_args):
  514. """Checks what gets registered as an unpacker."""
  515. # first make sure no other unpacker is registered for this extension
  516. existing_extensions = {}
  517. for name, info in _UNPACK_FORMATS.items():
  518. for ext in info[0]:
  519. existing_extensions[ext] = name
  520. for extension in extensions:
  521. if extension in existing_extensions:
  522. msg = '%s is already registered for "%s"'
  523. raise RegistryError(msg % (extension,
  524. existing_extensions[extension]))
  525. if not isinstance(function, Callable):
  526. raise TypeError('The registered function must be a callable')
  527. def register_unpack_format(name, extensions, function, extra_args=None,
  528. description=''):
  529. """Registers an unpack format.
  530. `name` is the name of the format. `extensions` is a list of extensions
  531. corresponding to the format.
  532. `function` is the callable that will be
  533. used to unpack archives. The callable will receive archives to unpack.
  534. If it's unable to handle an archive, it needs to raise a ReadError
  535. exception.
  536. If provided, `extra_args` is a sequence of
  537. (name, value) tuples that will be passed as arguments to the callable.
  538. description can be provided to describe the format, and will be returned
  539. by the get_unpack_formats() function.
  540. """
  541. if extra_args is None:
  542. extra_args = []
  543. _check_unpack_options(extensions, function, extra_args)
  544. _UNPACK_FORMATS[name] = extensions, function, extra_args, description
  545. def unregister_unpack_format(name):
  546. """Removes the pack format from the registry."""
  547. del _UNPACK_FORMATS[name]
  548. def _ensure_directory(path):
  549. """Ensure that the parent directory of `path` exists"""
  550. dirname = os.path.dirname(path)
  551. if not os.path.isdir(dirname):
  552. os.makedirs(dirname)
  553. def _unpack_zipfile(filename, extract_dir):
  554. """Unpack zip `filename` to `extract_dir`
  555. """
  556. try:
  557. import zipfile
  558. except ImportError:
  559. raise ReadError('zlib not supported, cannot unpack this archive.')
  560. if not zipfile.is_zipfile(filename):
  561. raise ReadError("%s is not a zip file" % filename)
  562. zip = zipfile.ZipFile(filename)
  563. try:
  564. for info in zip.infolist():
  565. name = info.filename
  566. # don't extract absolute paths or ones with .. in them
  567. if name.startswith('/') or '..' in name:
  568. continue
  569. target = os.path.join(extract_dir, *name.split('/'))
  570. if not target:
  571. continue
  572. _ensure_directory(target)
  573. if not name.endswith('/'):
  574. # file
  575. data = zip.read(info.filename)
  576. f = open(target, 'wb')
  577. try:
  578. f.write(data)
  579. finally:
  580. f.close()
  581. del data
  582. finally:
  583. zip.close()
  584. def _unpack_tarfile(filename, extract_dir):
  585. """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
  586. """
  587. try:
  588. tarobj = tarfile.open(filename)
  589. except tarfile.TarError:
  590. raise ReadError(
  591. "%s is not a compressed or uncompressed tar file" % filename)
  592. try:
  593. tarobj.extractall(extract_dir)
  594. finally:
  595. tarobj.close()
  596. _UNPACK_FORMATS = {
  597. 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"),
  598. 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
  599. 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file")
  600. }
  601. if _BZ2_SUPPORTED:
  602. _UNPACK_FORMATS['bztar'] = (['.bz2'], _unpack_tarfile, [],
  603. "bzip2'ed tar-file")
  604. def _find_unpack_format(filename):
  605. for name, info in _UNPACK_FORMATS.items():
  606. for extension in info[0]:
  607. if filename.endswith(extension):
  608. return name
  609. return None
  610. def unpack_archive(filename, extract_dir=None, format=None):
  611. """Unpack an archive.
  612. `filename` is the name of the archive.
  613. `extract_dir` is the name of the target directory, where the archive
  614. is unpacked. If not provided, the current working directory is used.
  615. `format` is the archive format: one of "zip", "tar", or "gztar". Or any
  616. other registered format. If not provided, unpack_archive will use the
  617. filename extension and see if an unpacker was registered for that
  618. extension.
  619. In case none is found, a ValueError is raised.
  620. """
  621. if extract_dir is None:
  622. extract_dir = os.getcwd()
  623. if format is not None:
  624. try:
  625. format_info = _UNPACK_FORMATS[format]
  626. except KeyError:
  627. raise ValueError("Unknown unpack format '{0}'".format(format))
  628. func = format_info[1]
  629. func(filename, extract_dir, **dict(format_info[2]))
  630. else:
  631. # we need to look at the registered unpackers supported extensions
  632. format = _find_unpack_format(filename)
  633. if format is None:
  634. raise ReadError("Unknown archive format '{0}'".format(filename))
  635. func = _UNPACK_FORMATS[format][1]
  636. kwargs = dict(_UNPACK_FORMATS[format][2])
  637. func(filename, extract_dir, **kwargs)